<template>
	<section class="scholl " >
		<div class="border-box">
			<div class="pt30rem pl30rem pb30rem fs20rem bg-f5">
				您还需要填写{{balance_count}}条评论				
			</div>	
			<div class="border-b20 experience-scroll-navbar bg-white">
				<!-- <div class="navbar-mask" style="">					
				</div>
				<scroll-navbar 
					id="navbar"
					:channels="nav_list" 
					key-name="column_name"  
					key-id="column_id" 
					v-model="selected"
				></scroll-navbar> -->
				<ul class="pl20rem pr20rem" id="scroll" ref="scroll">
					<li class="align-center fl" :class="{ active : selected == item.column_id }"  v-for="item in nav_list">
						{{ item.column_name }}
					</li>
				</ul>
			</div>		
			<ul class="bg-white">
				<li class="edit-star">
					<div class="align-center mb20rem">
						<i  class="ml20rem mr20rem iconfont icon-xingxing star-default" 
							v-for="(n,i) in 5"						
							:class="{'active': i < params.judge_star}"
							@click="chooseStar(i+1)"
						></i>	
					</div>
					<p class="align-center">
						{{explain_text}}
					</p>
				</li>
				<li class="pl30rem pr30rem align-right">
					<textarea 
						v-model="params.content"
						class="bg-f5 pt20rem pr10rem pb20rem pl10rem edit-textarea" 
						rows="6" 
						placeholder="请留下你的吐槽还有故事"
					></textarea>					 
				</li>
				<li class="pl30rem pr30rem pt20rem pb20rem align-right c999 fs24rem">需要15个字</li>
				<li class="pl30rem pr30rem pt30rem pb30rem align-left mb40rem">
					<div class="mb15rem flex-left flex-w">
						<div v-for="(img,index) in imgArray" class="evaluate-img mb25rem border mr40rem">
							<img :src="img" class="responsive-img">
							<button class="delete-img" @click="removeImg(index)">×</button>
						</div>	
						<div class="upload-img bg-f5 white fs32" 
								@click="uploadImg" 
								v-show="imgArray.length < max_num"
							>
							<!-- <input type="file" id="img" name='avatar' multiple="multiple" @change="uploadFile" class="hide">	 -->		
							<input type="file" id="img" name='avatar' @change="uploadFile" class="hide">					
						</div>
					</div>
					<div class="align-right">
						<small class="c999">
							图片最多上传{{max_num}}张
						</small>
					</div>					
				</li>
			</ul>
			<div class="pl30rem pr30rem pb30rem">
				<button 
					@click="nextFun"
					class="next-button white align-center pt20rem pb20rem">
					下一步
				</button>
			</div>
			
		</div>
	</section>
</template>
<script>
	import ScrollNavbar 	from '@/components/Scroll-navbar';
	import { uploadAvatar } from "@/utils";
	import $toast 			from '@/utils/toast';
	import { showExprienceColumn, ExprienceReport, handlerExprienceImages } from "@/api/ordering";
	import { getWechatConfig } from '@/api/goods-detail';

	export default 
	{	
		components: 
		{
			ScrollNavbar
		},					
		data()
		{
			return{
				balance_count: 0,
				selected	 : 0,
				explain_text : '非常满意',
				imgArray	 : [],
				max_num		 : 6,
				nav_list	 : [],
				key          : 0,
				css_num  	 : 1,
				i            : 0,
				images : {
		            localId: [],
		            serverId: []
		        },
				params: 
				{
					uid 		: Number(localStorage.getItem('uid')), 
					sku_id		: Number(this.$route.query.sku_id),
					judge_id	: Number(this.$route.query.judge_id),
					column_id	: 0,
					judge_star  : 5,
					content		: '',
					order_id	: Number(this.$route.query.order_id),
				},
				imgParams: 
				{
					uid 		: Number(localStorage.getItem('uid')), 
					goods_id	: Number(this.$route.query.goods_id),
					judge_id	: Number(this.$route.query.judge_id),
					order_id	: Number(this.$route.query.order_id),
					column_id	: 0,
					images		: '',
					
				}
			}
		},
		updated()
		{
			 this.$nextTick(() => {
			 	this.$refs.scroll.style.width = this.nav_list.length * 85 + 'px';
			 	console.log(this.nav_list.length)
			 	console.log(this.$refs.scroll.offsetWidth);
            })
		},
		methods: 
		{
			chooseStar(num)
			{
				this.params.judge_star  = num;
				if(num <= 1)
				{
					this.explain_text = '差评';
				}
				else if(num <= 3)
				{
					this.explain_text = '一般';
				}
				else if(num <= 4)
				{
					this.explain_text = '满意';
				}
				else if(num = 5)
				{
					this.explain_text = '非常满意';
				}	

			},
			uploadImg()
			{
				wx.ready( ()=> {
	                wx.checkJsApi({
	                    jsApiList: [
	                        'chooseImage',
	                        'previewImage',
	                        'uploadImage',
	                        'downloadImage'
	                    ],
	                    success:  res => {
	                        //alert(JSON.stringify(res));
	                        //alert(JSON.stringify(res.checkResult.getLocation));
	                        if (res.checkResult.getLocation == false) {
	                            alert('你的微信版本太低，不支持微信JS接口，请升级到最新的微信版本！');
	                            return;
	                        }else{
	                            this.wxChooseImage();
	                        }
	                    }
	                });
	            });
	            wx.error(function(res){
	                // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
	                alert("验证失败，请重试！");
	                wx.closeWindow();
	            });
			},
			//拍照或从手机相册中选图接口
	        wxChooseImage() {
				this.i = 0;
	            wx.chooseImage({
	            	count: 6, // 默认9
	            	sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], 
	                success: res => {
	                    this.images.localId = res.localIds;
	                    this.images.serverId = [];
	            		// var i = 0, length = this.images.localId.length;
	                    this.upload(this.images.localId,this.images.serverId);
	                }
	            });
	        },
	        upload(img_local,img_server) {
                //图片上传
                wx.uploadImage({
                    localId: img_local[this.i],
                    success: res => {
                        this.i++;
                        img_server.push(res.serverId);
                        //图片上传完成之后，进行图片的下载，图片上传完成之后会返回一个在腾讯服务器的存放的图片的ID--->serverId
                        wx.downloadImage({
                            serverId: res.serverId, // 需要下载的图片的服务器端ID，由uploadImage接口获得
                            isShowProgressTips: 1, // 默认为1，显示进度提示
                            success:  res => {
                                var localId = res.localId; // 返回图片下载后的本地ID
                                //通过下载的本地的ID获取的图片的base64数据，通过对数据的转换进行图片的保存
                                wx.getLocalImgData({
                                    localId: localId, // 图片的localID
                                    success:  res => {
                                        var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                                        var u = navigator.userAgent;
                                        if (u.indexOf('iPhone') > -1 || u.indexOf('iPad') > -1 || u.indexOf('ios') > -1 ) {
                                        	localData = localData.replace('jpg','jpeg');
                                        	this.imgArray.push(localData)
                                        } else {
                                        	localData = 'data:image/jpeg;base64,' +  localData
                                        	this.imgArray.push(localData)
                                        }
                                    }
                                });
                            }
                        });
                        if (this.i < img_local.length) {
                            this.upload(img_local,img_server);
                        }
                    },
                    fail: function(res) {
                        alert(JSON.stringify(res));
                    }
                });
            },
			uploadFile()
			{
				/*uploadAvatar("img", res => {
					this.imgArray.push(res);
					this.imgParams.column_id = this.nav_list[this.key].column_id;	
					this.imgParams.images    = this.imgArray.join('|');
					//handlerExprienceImages(this.imgParams).then(res=>{});	
				});*/
				this.imgParams.column_id = this.nav_list[this.key].column_id;	
				this.imgParams.images = this.imgArray.join('|');
				handlerExprienceImages(this.imgParams).then(res=>{});	
			},
			removeImg(index){
				this.imgArray.splice(index,1);
			},
			initParams()
			{
				++this.key;
				this.selected = this.nav_list[this.key].column_id;
				this.params.judge_star = 5;
				this.explain_text = '非常满意'
				this.params.content = '';
				this.imgArray = [];
			},
			nextFun()
			{
				this.params.column_id = this.nav_list[this.key].column_id;
				ExprienceReport(this.params).then( res=>{
					this.balance_count--;
					if( this.balance_count == 0)
					{
						$toast("评论成功");
						this.$router.push("/member/experienceStar/");
					}
					else
					{
						this.initParams();
					}					
				});
				//超过索引为3的栏目，就向左滑动
				if(this.nav_list.length > 4 && this.key > 2)
				{
					document.getElementById('navbar').style.left = "-"+this.css_num*6+"rem";
					this.css_num++;
				}
			},
			getWXconfig()
			{
				let url = location.href.split('#')[0] //获取锚点之前的链接
		        getWechatConfig(url).then(resData => {
			        wx.config({
					    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
					    appId: resData.data.appId, // 必填，公众号的唯一标识
					    timestamp: resData.data.timestamp, // 必填，生成签名的时间戳
					    nonceStr: resData.data.nonceStr, // 必填，生成签名的随机串
					    signature: resData.data.signature,// 必填，签名
					    jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'] // 必填，需要使用的JS接口列表
					});
		        });
			}						
		},
		
		created()
		{
			showExprienceColumn(this.params.uid, this.imgParams.goods_id).then( res =>{
				this.nav_list = res.data;
				this.selected = res.data[0].column_id;
				this.balance_count = this.nav_list.length;
			});
			this.getWXconfig();
		},
	}
</script>

<style lang="less">
	.border-box{
		box-sizing: border-box;		
		.edit-star{
			height: 300/28rem;
			padding-top: 80/28rem;
			.icon-xingxing{
				font-size: 54/28rem;
			}
			.star-default{
				color: #d6d6d6;
			}
			.active{
				color: #FB8E01 !important;
			}
		}
		
		.edit-textarea{
			border: 1px solid transparent;
			width: 100%;
			resize: none;
		}
		.next-button{
			width: 100%;
			background-color: #ff0036;
			border-radius: 5px;
		}
		.upload-img{
			width: 160/28rem;
			height: 160/28rem;
			position: relative;
		}
		.evaluate-img{
			width: 160/28rem;
			height: 160/28rem;
			position: relative;
			img{
				height: 100%;
				object-fit: cover;
			}
		}
		.upload-img:after{
			position: absolute;
			content: '+';
			display: inline-block;
			font-size: 3rem;
			color: #999;
			font-weight: 200;
			top: 50%;
			left: 50%;
			transform: translate(-50%,-50%);
		};
		.delete-img{
			display: inline-block;
		    position: absolute;
		    width: 20px;
		    height: 20px;
		    background-color: #ccc;
		    border-radius: 100%;
		    color: #eee;
		    right: -1rem;
		    top: -1rem;
		}
		.experience-scroll-navbar{
	        width: 100%;
	        box-sizing: border-box;
	        background: #FFF;
	        overflow-x:scroll; 
			ul{
				height: 100/28rem;
	        	line-height: 100/28rem;
	        	font-size: 1rem;
	        	overflow-x: scroll; 
	        	overflow-y: hidden;
				li{
					width: 80px;
				}
				.active{
					position: relative;
					color: #ff0036;
				}
				.active:before{
					content:'';
					width: 3rem;
					height: 3px;
					background-color: #ff0036;
					display: block;
					position: absolute;
					bottom:0;
					left: 50%;
					transform: translate(-50%,50%);
				}
			}
		}
	}	
	.border-box * {
		box-sizing: border-box;
	}
	.hide{
		display: none;
	}
	
	
</style>

